package com.nageoffer.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nageoffer.shortlink.admin.common.convention.exception.ClientException;
import com.nageoffer.shortlink.admin.common.convention.exception.ServiceException;
import com.nageoffer.shortlink.admin.common.enums.UserErrorCodeEnum;
import com.nageoffer.shortlink.admin.config.RBloomFilterConfiguration;
import com.nageoffer.shortlink.admin.dao.entity.UserDO;
import com.nageoffer.shortlink.admin.dao.mapper.UserMapper;
import com.nageoffer.shortlink.admin.dto.req.UserLoginReqDTO;
import com.nageoffer.shortlink.admin.dto.req.UserRegisterReqDTO;
import com.nageoffer.shortlink.admin.dto.req.UserUpdateReqDTO;
import com.nageoffer.shortlink.admin.dto.resp.UserLoginRespDTO;
import com.nageoffer.shortlink.admin.dto.resp.UserRespDTO;
import com.nageoffer.shortlink.admin.service.GroupService;
import com.nageoffer.shortlink.admin.service.UserService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import static com.nageoffer.shortlink.admin.common.constant.RedisCacheConstant.LOCK_USER_REGISTER_KEY;
import static com.nageoffer.shortlink.admin.common.enums.UserErrorCodeEnum.*;


@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {

    // 布隆过滤器，用于防止缓存穿透（预检查用户名是否存在）
    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;
    // 分布式锁客户端
    private final RedissonClient redissonClient;
    // Redis操作模板
    private final StringRedisTemplate stringRedisTemplate;
    // 分组服务
    private final GroupService groupService;

    @Override
    public UserRespDTO getUserByUsername(String username) {
        // 构建查询条件：按用户名查询未删除用户
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, username);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        // 用户不存在时抛出异常
        if (userDO == null) {
            throw new ServiceException(UserErrorCodeEnum.USER_NULL);
        }
        // 实体转换（DO -> DTO）
        UserRespDTO result = new UserRespDTO();
        BeanUtils.copyProperties(userDO, result);
        return result;
    }

    @Override
    public Boolean hasUsername(String username) {
        // 通过布隆过滤器判断用户名是否可能已存在（反向逻辑）
        return !userRegisterCachePenetrationBloomFilter.contains(username);
    }

    @Override
    public void register(UserRegisterReqDTO requestParam) {
        // 前置检查：用户名已存在时抛出异常
        if (!hasUsername(requestParam.getUsername())) {
            throw new ClientException(USER_NAME_EXIST);
        }
        // 获取用户名粒度的分布式锁（防止并发注册）
        RLock lock = redissonClient.getLock(LOCK_USER_REGISTER_KEY + requestParam.getUsername());
        try {
            if (lock.tryLock()) {
                try {
                    // 插入用户数据
                    int inserted = baseMapper.insert(BeanUtil.toBean(requestParam, UserDO.class));
                    // 插入失败处理
                    if (inserted < 1) {
                        throw new ClientException(USER_SAVE_ERROR);
                    }
                } catch (DuplicateKeyException ex) {
                    // 处理唯一键冲突
                    throw new ClientException(USER_EXIST);
                }
                // 将新用户名加入布隆过滤器
                userRegisterCachePenetrationBloomFilter.add(requestParam.getUsername());
                // 为新用户创建默认分组
                groupService.saveGroup(requestParam.getUsername(),"默认分组");
                return;
            }
            throw new ClientException(USER_NAME_EXIST);
        } finally {
            // 确保锁释放
            lock.unlock();
        }
    }

    @Override
    public void update(UserUpdateReqDTO requestParam) {
        // TODO 验证当前用户名是否为登录用户（待实现的安全校验）
        // 构建更新条件：按用户名更新
        LambdaUpdateWrapper<UserDO> updateWrapper = Wrappers.lambdaUpdate(UserDO.class)
                .eq(UserDO::getUsername, requestParam.getUsername());
        // 执行更新操作
        baseMapper.update(BeanUtil.toBean(requestParam, UserDO.class), updateWrapper);
    }

    @Override
    public UserLoginRespDTO login(UserLoginReqDTO requestParam) {
        // 构建查询条件：用户名+密码+未删除状态
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, requestParam.getUsername())
                .eq(UserDO::getPassword, requestParam.getPassword())
                .eq(UserDO::getDelFlag, 0);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        // 用户不存在或密码错误
        if (userDO == null) {
            throw new ClientException("用户不存在");
        }
        // 从Redis获取用户所有活跃会话的Hash结构（Key: Token, Value: 会话信息）
        Map<Object, Object> hasLoginMap = stringRedisTemplate.opsForHash()
                .entries("login_" + requestParam.getUsername());

        // 检查是否存在活跃会话
        if (CollUtil.isNotEmpty(hasLoginMap)) {
            // 获取第一个Token（Hash的Field）
            String token = hasLoginMap.keySet().stream()
                    .findFirst()  // 取第一个Key（Token）
                    .map(Object::toString)  // 转为String类型
                    .orElseThrow(() -> new ClientException("用户登录错误"));  // 异常处理

            // 返回已存在的Token
            return new UserLoginRespDTO(token);
        }
        //不用stream流 比较传统的写法
        /*if (CollUtil.isNotEmpty(hasLoginMap)) {
            // 获取Hash结构的所有Key（Token集合）
            Set<Object> tokenSet = hasLoginMap.keySet();
            // 通过迭代器获取第一个Token
            Iterator<Object> iterator = tokenSet.iterator();
            if (iterator.hasNext()) {
                String token = iterator.next().toString();
                return new UserLoginRespDTO(token);
            }
            throw new ClientException("用户登录错误");
        }*/
        // 生成唯一Token作为登录凭证
        String uuid = UUID.randomUUID().toString();
        // 存储登录信息到Redis（Hash结构）
        stringRedisTemplate.opsForHash().put("login_" + requestParam.getUsername(), uuid, JSON.toJSONString(userDO));
        // 设置30天过期时间
        stringRedisTemplate.expire("login_" + requestParam.getUsername(), 30L, TimeUnit.MINUTES);
        return new UserLoginRespDTO(uuid);
    }

    @Override
    public Boolean checkLogin(String username, String token) {
        // 检查Redis中是否存在对应的Token
        return stringRedisTemplate.opsForHash().get("login_" + username, token) != null;
    }

    @Override
    public void logout(String username, String token) {
        // 验证Token有效性后执行登出
        if (checkLogin(username, token)) {
            // 删除Redis中的登录记录
            stringRedisTemplate.delete("login_" + username);
            return;
        }
        throw new ClientException("用户Token不存在或用户未登录");
    }
}